<?php

/**
 * 科大讯飞人脸认证
 */
class Face {
    private $appId;
    private $apiKey;

    public function __construct() {
        $this->appId='156e51ae';
        $this->apiKey='986063ab4c51f78e45c5e24a1a67b967';
    }


    public function verify($image1,$image2) {
        $api = "http://api.xfyun.cn/v1/service/v1/image_identify/face_verification";
        $XAppid = $this->appId;
        $Apikey = $this->apiKey;
        $XCurTime =time();
        $Param= array("auto_rotate"=>true,);
        $image1=file_get_contents(cdnurl($image1));
        $image1=base64_encode($image1);
        $image2=file_get_contents(cdnurl($image2));
        $image2=base64_encode($image2);
        $Post = array('first_image' => $image1, 'second_image' => $image2,);

        $XParam = base64_encode(json_encode($Param));
        $XCheckSum = md5($Apikey.$XCurTime.$XParam);
        $headers = array();
        $headers[] = 'X-CurTime:'.$XCurTime;
        $headers[] = 'X-Param:'.$XParam;
        $headers[] = 'X-Appid:'.$XAppid;
        $headers[] = 'X-CheckSum:'.$XCheckSum;
        $headers[] = 'Content-Type:application/x-www-form-urlencoded; charset=utf-8';
        $result=$this->http_request($api, $Post, $headers);
        if(!$result) return ['code'=>0,'msg'=>'网络繁忙'];
        $response = json_decode($result,true);
        if(isset($response['code']) && $response['code']=='0'){
            return ['code'=>1,'msg'=>'success','data'=>$response['data']];
        }else{
            //return ['code'=>0,'msg'=>$response['code'].':'.$response['desc']];
            return ['code'=>0,'msg'=>'验证失败'];
        }
    }
    function http_request($url, $post_data, $headers) {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => $headers,
                'content' => $postdata,
                'timeout' => 15*60
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

}